package database

import (
	"api-fiber-gorm/model"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"strings"
	"time"
)

var (
	DB *gorm.DB
)

// ConnectDB connect to db
func ConnectDB() {
	var err error
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 日志级别 Silent
			IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,       // 禁用彩色打印
		},
	)
	db, err := gorm.Open(mysql.New(mysql.Config{
		//DriverName: "my_mysql_driver",
		DSN: "root:Dbuser@123!@tcp(192.168.0.55:3306)/test?charset=utf8&parseTime=True&loc=Local",
	}), &gorm.Config{}, &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "t_",                              // table name prefix, table for `User` would be `t_users`
			SingularTable: true,                              // use singular table name, table for `User` would be `user` with this option enabled
			NoLowerCase:   true,                              // skip the snake_casing of names
			NameReplacer:  strings.NewReplacer("CID", "Cid"), // use name replacer to change struct/field name before convert it to db name
		}})
	if err != nil {
		return
	}

	fmt.Println("Connection Opened to Database")
	db.AutoMigrate(&model.Product{}, &model.User{}, &model.Address{}, &model.Goods{}, &model.Order{}, &model.Message{})
	fmt.Println("Database Migrated")
	DB = db
}
